/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.sais.eswn.deck;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import org.sais.eswn.tool.Tools;
import org.sais.eswn.card.Card;

public class Deck {

    private ArrayList<String> mCards = new ArrayList<String>();
    public String mDeckname = "";

    public Deck() {
    }

    public Deck(String deckname, ArrayList<String> spells) {
        setDeck(deckname, spells);
    }

    public void setDeck(String deckname, ArrayList<String> cards) {
        mDeckname = deckname;
        mCards = cards;
    }

    public void setDeckname(String deckname) {
        mDeckname = deckname;
    }

    public String getDeckname() {
        return mDeckname;
    }

    public String listCardnosForSock() {
        String ret = "";
        for (String s : listCardnos()) {
            ret += s + " ";
        }
        if (ret.length() > 0) {
            return ret.substring(0, ret.length() - 1);
        } else {
            return "";
        }
    }

    public ArrayList<String> listCardnos() {
        ArrayList<String> ret = new ArrayList<String>();
        ret.addAll(mCards);
        return ret;
    }

    public void add(String no) {
        Card c = Tools.getCard(no);
        if (c == null) {
            return;
        }
        if (!mCards.contains(no)) {
            mCards.add(no);
        }
    }

    public boolean save(File file) {
        try {
            BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"), 8192);
            // deckname
            out.write(mDeckname + "\n");
            // cards
            out.write(String.valueOf(mCards.size()) + "\n");
            for (String c : mCards) {
                out.write(c + "\n");
            }
            out.flush();
            out.close();
            return true;
        } catch (IOException e) {
            System.out.println(e);
            return false;
        }

    }

    public static Deck load(
            File file) {
        try {
            String deckname;
            ArrayList<String> cards = new ArrayList<String>();

            BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"), 8192);
            // deckname
            deckname = in.readLine();
            // spells
            int spell_cnt = Integer.parseInt(in.readLine());
            for (int i = 0; i <
                    spell_cnt; ++i) {
                cards.add(in.readLine());
            }
            in.close();
            return new Deck(deckname, cards);
        } catch (Exception e) {
            System.out.println(e);
            return null;
        }
    }
}

